package cn.py.boot_lua.controller.test;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FilesSize {

    public static void main(String[] args) {
       /* List<String> list = Arrays.asList("https://pushimg.liecaizhijia.com/ai_domain//2025-07-11/9846947a-a8e7-4cfb-871f-4cdf2eca8a11.mp4");
        filesSizeSum(list);*/


        Map<String, Integer> videoSize = getVideoSize("https://pushimg.liecaizhijia.com/adminshop/20250321/96aa662837bc9cdb639e3aee8ad54a9e.png");
        System.out.println(videoSize);
    }

    public static void filesSizeSum(List<String> list){
        int sum = 0;
        for (String url : list){
            int size = getFilesSize(url);
            sum += size;
        }
        if (sum > 300){
            throw new RuntimeException("保证上传视频的总的视频大小不能大于300MB");
        }
        System.out.println(sum);
    }

    public static int getFilesSize(String fileUrl) {
        int size = 0;
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("HEAD");
            int fileSize = connection.getContentLength();
            if (fileSize < 0) {
                throw new RuntimeException("上传的文件有误,请重试");
            } else {
                double fileMB= fileSize / (1024.0 * 1024.0);
                size = (int) Math.ceil(fileMB);
            }
            connection.disconnect();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return size;
    }


    private static Map<String, Integer> getVideoSize(String imgURL) {
        Map<String, Integer> map = new HashMap<>();

        // 从网络路径直接打开输入流
        try (InputStream in = new URL(imgURL).openStream()) {
            BufferedImage image = ImageIO.read(in); // 直接从流中读取图片
            if (image == null) {
                throw new IOException("无法识别图片格式或图片损坏");
            }

            int width = image.getWidth();
            int height = image.getHeight();

            map.put("width", width);
            map.put("height", height);
        } catch (Exception e) {
            throw new RuntimeException("获取图片参数失败: " + e.getMessage());
        }

        return map;
    }


}
